#-- vim:sw=2:et
#++
#
# :title: Simple stock lookup plugin for RBot and Google
# :author: Jason Hines, <jason@greenhell.com>
# :version: 0.1
#

# GOOGLE returns JSON
# http://www.google.com/finance/info?q=C
# // [
# {
# "id": "662713"
# ,"t" : "C"                      # symbol
# ,"e" : "NYSE"                   # market
# ,"l" : "17.75"                  # last
# ,"l_cur" : "17.75"
# ,"ltt":"4:10PM EDT"
# ,"lt" : "Sep 29, 4:10PM EDT"    # time
# ,"c" : "-2.40"                  # change
# ,"cp" : "-11.91"                # change percent
# ,"ccol" : "chr"
# ,"el": "17.84"                  # after-hours last
# ,"el_cur": "17.84"
# ,"elt" : "Sep 29, 4:52PM EDT"   # after-hours time
# ,"ec" : "+0.09"                 # after-hours change
# ,"ecp" : "0.51"                 # after-hours change percent
# ,"eccol" : "chg"
# }
# ]
require 'json'

class StockPlugin < Plugin

  B = 2.chr

  def stock(m, params)
    symbol = params[:symbol].to_s

    resp = @bot.httputil.get("http://www.google.com/finance/info?q=#{symbol}")
    resp = resp.sub(/\/\/\s\[/,'')
    resp = resp.sub(/\]/,'')
    data = JSON.parse(resp)

    symbol = data['t']
    last = data['l']
    change = data['c']
    time = data['lt']
    change = data['c']
    percent = data['cp']

    elast = data['el']
    etime = data['elt']
    echange = data['ec']
    epercent = data['ecp']

    m.reply "[#{B}#{symbol}#{B}] Last: #{B}#{last}#{B}, Change: #{change} (#{percent}%) [#{time}]"
    m.reply "=> (After Hours) Last: #{B}#{elast}#{B}, Change: #{echange} (#{epercent}%) [#{etime}] " unless data['el'].nil?
  end

  def help(plugin, topic="")
    "stock <symbol> => lookup stock information about <symbol>"
  end

end

plugin = StockPlugin.new

plugin.map "stock :symbol"
